"use strict"

async function onLogin(){
    Table_Show()

}


function decodeFunction(fragment, resultData, decimals ){

    const iface = new window._ethers.utils.Interface(Contract_VOOK_Abi);
    try
    {
        const result = iface.decodeFunctionData(fragment , resultData )
        console.log(result);

        const func   = fragment
        const to     = result.recipient

        console.log(func,to);

        return {func:func,to:to};
    }
    catch(e)
    {
        console.log(e);
        return null;
    }
}


function getData(n){
    n=new Date(n)
    return n.toLocaleDateString().replace(/\//g, "-") + " " + n.toTimeString().substr(0, 8)
}

function getCountdown(timestamp){
    var nTime = new Date().getTime();
    var t = timestamp - nTime;
    if(t<=0) t = 0;

    var d=Math.floor(t/1000/60/60/24);
    var h=Math.floor(t/1000/60/60%24);
    var m=Math.floor(t/1000/60%60);
    var s=Math.floor(t/1000%60);
    let  GMT = d + ' Day '+ h +':'+ m  + ':' + s;
    GMT = GMT.replace(/0:/g,"").replace(/0 Day /g,"").replace(/-/g,"");
    return GMT;
}

async function Table_Show()
{
    const contract = new window._ethers.Contract(Contract_VOOK, Contract_VOOK_Abi, Helper.provider.getSigner());
    var tx  = await contract.multiSigTranLen();

    dataCountMax = window._ethers.utils.formatUnits(tx, 0)

    var html = "Showing frist to last of maxcount entries";
    html = html.replace(/frist/g, (dataOffset+1).toString());
    html = html.replace(/last/g, (dataOffset+dataCount).toString());
    html = html.replace(/maxcount/g, dataCountMax);
    $("#recordtable_info").html( html );
    paginate_button();

    dataRecord = {};
    var index = 0;

    // 删除之前的数据
    var mytableEle = document.getElementById("recordtable");
    for (var i = mytableEle.children.length - 1; i >= 0; i--) {
        if (mytableEle.children[i].id.indexOf("_table111") == -1)
            mytableEle.children[i].remove();
    }
    
    for (var ii = dataOffset ; ii < dataCount+dataCount && ii < dataCountMax ; ii++) {
        
        var tx  = await contract.transactions(ii);
        console.log("transactions",tx);

        var item = {};
        item.index = ii;
        // item.executed = tx.executed;
        item.executed = tx.executed;

        var decode = decodeFunction("withdraw",tx.data);

        if(decode==null){
            continue;
        }

        item.Tranfer = decode.func + " to " + decode.to;

        item.numConfirm = window._ethers.utils.formatUnits(tx.numConfirmations, 0)
        var locktime = window._ethers.utils.formatUnits(tx.locktime, 0)
        item.locktime = getData( Number.parseFloat(locktime)*1000 );

        if(tx.executed==false){
            item.executed = getCountdown( Number.parseFloat(locktime)*1000 );
            if( item.executed == "0" ) item.executed = "unexecuted";
        }else{
            item.executed = "executed";
        }

        TableInsert("recordtable", "rtr-"+ii, index++, item)

        dataRecord[ii] = item;
    }
    onRunTable_Show = false;
}


async function liOnclick(e){
    ShowModalSetting( e.id.replace(/rtr-/g, "") );

    $("#Set_Delete").html("Execute")
    $("#Set_Submit").html("Confirm")
    {
        $("#Set_Delete").removeClass('btn');
        $("#Set_Delete").addClass('blogcradbtnDis');
        $("#Set_Delete").attr("onclick","");

        $("#Set_Submit").removeClass('btn');
        $("#Set_Submit").addClass('blogcradbtnDis');
        $("#Set_Submit").attr("onclick","");
    }

    const contract = new window._ethers.Contract(Contract_VOOK, Contract_VOOK_Abi, Helper.provider.getSigner());
    var isOwner  = await contract.isOwner(Helper.addressCur);

    var item = dataRecord[ Number.parseInt(e.id.replace(/rtr-/g, "")) ];
    var tx  = await contract.transactions(item.index);
    var locktime = window._ethers.utils.formatUnits(tx.locktime, 0)

    var timestamp = (await Helper.provider.getBlock()).timestamp;
    if(!isOwner) return;
    if(!item.executed=="executed") return;

    var tx  = await contract.isConfirmed( item.index , Helper.addressCur);
    if(tx!=true){
        $("#Set_Submit").addClass('btn');
        $("#Set_Submit").removeClass('blogcradbtnDis');
        $("#Set_Submit").attr("onclick","onConfirm(this)");
    }
    else if(timestamp>locktime){
        var required  = await contract.numConfirmationsRequired();
        if(required<=item.numConfirm){
            $("#Set_Delete").addClass('btn');
            $("#Set_Delete").removeClass('blogcradbtnDis');
            $("#Set_Delete").attr("onclick","onExecute(this)");
        }
    }
    $("#Set_Submit").attr('data',item.index);

}

async function onExecute(e){
    try{
        const contract = new window._ethers.Contract(Contract_VOOK, Contract_VOOK_Abi, Helper.provider.getSigner());
        var index = $("#Set_Submit").attr('data');
        var tx  = await contract.executeTransaction( index );
        alert("Execute OK");
        $("#Set_Delete").removeClass('btn');
        $("#Set_Delete").addClass('blogcradbtnDis');
    }
    catch(er){
        console.log(er)
        alert(er.toString());
    }
}

async function onConfirm(e){
    try{
        const contract = new window._ethers.Contract(Contract_VOOK, Contract_VOOK_Abi, Helper.provider.getSigner());
        var index = $("#Set_Submit").attr('data');
        var tx  = await contract.confirmTransaction( index );
        $("#Set_Submit").removeClass('btn');
        $("#Set_Submit").addClass('blogcradbtnDis');
        alert("Confirm OK");
    }
    catch(er){
        console.log(er)
        alert(er.toString());
    }
}

var onRunTable_Show = false;
function onNavClick(e)
{
    if(onRunTable_Show){
        return ;
    }
    onRunTable_Show = true;
    setTimeout("onRunTable_Show=false;", 3000);

    var panechild = $(e).parent().find(".active");
    for (var ii=0;ii<panechild.length;ii++){
        $(panechild[ii]).removeClass("active");
    }

    $(e).addClass("active");

    var pane = $(e).html().replace(/ &amp; /g, "-").replace(/ /g, "-").replace(/[\t\r\f\n\s]*/g,'');

    if(pane=="OPK"){
        pane = "OPK";
        if( Helper.addressCur!=null ){
            Table_Show()
        }
    }
    else{
        onRunTable_Show=false;
    }

    var content = $("#"+pane).parent();
    if(content[0]){
        var panechild = content[0].children;
        for (var ii=0;ii<panechild.length;ii++){
            $(panechild[ii]).removeClass("show");
            $(panechild[ii]).removeClass("active");
        }
        
        $(".tab-content #"+pane).addClass("show");
        $(".tab-content #"+pane).addClass("active");
    }

}

function select_dropdownitem(e)
{
  var parent_btn_group = $(e).parents(".btn-group");
  parent_btn_group.find("#select_image").attr("src", $(e).find('.row .col img').attr("src"));
  parent_btn_group.find("#select_name").html($(e).find('.row .col').text().replace(/[\t\r\f\n\s]*/g,''));

  var parent_html = $(e).parents(".modal-content").find(".nav-tabs .nav-item .active");
  if( parent_html.attr("id") == "cashout-tab")
  {
    console.log(parent_btn_group.find("#select_name").html());
    if( parent_btn_group.find("#select_name").html() == "USDT" )
    {
      $("#cashout_amount_cur").html( $('#head_amount').html() );
    }
    else
    if( parent_btn_group.find("#select_name").html() == "USDC" )
    {
      $("#cashout_amount_cur").html( "0" );
    }
  }
}

async function onSubmitTransaction(e)
{
    try{
        const select_Type     = $("#Submit #select_Type .dropdown-text").html();

        const input_address = $("#tranfer #input_address").val()
        
        const Contract_addr = Contract_VOOK;

        const iface = new window._ethers.utils.Interface(Contract_VOOK_Abi);
        const data  = iface.encodeFunctionData(select_Type, [input_address])

        const contract = new window._ethers.Contract(Contract_VOOK, Contract_VOOK_Abi, Helper.provider.getSigner());
        var isOwner  = await contract.isOwner(Helper.addressCur);
        if(!isOwner){
            alert("You are not the owner");
            return;
        }
        var tx  = await contract.submitTransaction(Contract_addr,0,data);
        var rel = await tx.wait();
        alert("Submit OK");
    }
    catch(er){
        alert(er.toString());
        return;
    }
}

(function($) {
    console.log("multiSigWallet.js",777);

    
})(jQuery);


